﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace gt.framework.Security
{
    public class RSAPublicKey
    {
        public byte[] Modulus { get; set; }
        public byte[] Exponent { get; set; }

        public string ModulusText { get; set; }
        public string ExponentText { get; set; }

        public static RSAPublicKey FromXmlString(string xmlString)
        {
            if (string.IsNullOrEmpty(xmlString)) return null;
            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
                {
                    if (!reader.ReadToFollowing("RSAKeyValue")) return null;
                    if (reader.LocalName != "Modulus" && !reader.ReadToFollowing("Modulus")) return null;
                    RSAPublicKey publicKey = new RSAPublicKey();
                    publicKey.ModulusText = reader.ReadElementContentAsString();

                    if (reader.LocalName != "Exponent" && !reader.ReadToFollowing("Exponent")) return null;
                    publicKey.ExponentText = reader.ReadElementContentAsString();

                    publicKey.Modulus = Convert.FromBase64String(publicKey.ModulusText);
                    publicKey.Exponent = Convert.FromBase64String(publicKey.ExponentText);

                    return publicKey;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
